$("#hidechartdiv").hide();

$('.form_datetime').datetimepicker({
	format: "yyyy-mm-dd hh:ii:ss",
	language: 'zh-CN',
	todayBtn: 1,
	autoclose: 1,
	todayHighlight: 1,
	startView: 2,
	forceParse: 0,
	showMeridian: 1,
	endDate: new Date(),
});

$('.selectpicker').selectpicker('val', 'mustard');
$('.selectpicker').selectpicker('val', ['mustard', 'relish']);
$('.selectpicker').selectpicker('refresh');

$(function () {
	//查询所有车间
	$.ajax({
        type: 'get',
        url: '/chart/queryLocationByBusinessId',
        data: {
            'businessId': label_id
        },
        dataType: 'json',
        async: false,
        contentType: "application/json; charset=utf-8",
        success: function (res) {
            let data = res.data
            $('#work_id').empty();
            for (var i = 0; i < data.length; i++) {
                $("#work_id").append(
                    "<option value='" + data[i] + "'>" + data[i] +
                    "</option>");
            }
			$("#work_id").selectpicker("refresh");
        },
    });
	//选用change事件，当对select 1选择option时都会及时响应2的结果
	$('#work_id').change(function () {
		//清除之前缓存数据
		$('#select_no').empty();
		$("#select_no").selectpicker("refresh");
		$('#select_type').empty();
		$("#select_type").selectpicker("refresh");
		var workshop_values = $("#work_id").val();
		if(workshop_values == null) {
			return
		}
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
//   		console.log(workshop)
		techProcessId = "techProcessId=" + label_id
		//根据车间查类型
		$.ajax({
			type: 'get',
			url: '/warning_record/querysortbyworkshop?'+ techProcessId + "&" + workshop,
			async: false,
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_no").append(
						"<option value='" + data[i] + "'>" +
						data[i] + "</option>");
				}
				$("#select_no").selectpicker("refresh");
			}
		});
	});
	$('#select_no').change(function () {
		//清除之前缓存数据
		$('#select_type').empty();
		$("#select_type").selectpicker("refresh");
		var workshop_values = $("#work_id").val();
		var workshop = new Array();
		for (var i = 0; i < workshop_values.length; i++) {
			workshop[i] = 'workshop=' + workshop_values[i];
		}
		workshop = workshop.join('&');
		var sort = $("#select_no").val();
		sort = 'sort=' + sort;
		//根据车间和类型查传感器编号
		techProcessId = "techProcessId=" + label_id
		$.ajax({
			type: 'get',
			url: '/warning_record/querysensorrowidbyworkshopandsort?'+ techProcessId + "&" + workshop + '&' + sort,
			async: false,
			success: function (data) {
				for (var i = 0; i < data.length; i++) {
					$("#select_type").append(
						"<option value='" + data[i] + "'>" +
						data[i] + "</option>");
				}
				$("#select_type").selectpicker("refresh");
			}
		});
	});
});

$("#btn_return").click(function () {
	$('#page-wrapper').load('pages/technological_process.html');
})

$("#search").click(
	function (event) {
		var workshop = $("#work_id").val();
		var sort = $("#select_no").val();
		var SENSOR_ROW_ID = $("#select_type").val();
		var startTime = $("#starttime").val();
		var endTime = $("#endtime").val();
		if (workshop == null) {
			bootoast({
				message: '请选中车间名称',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (sort == null) {
			bootoast({
				message: '请选中设备类型',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (SENSOR_ROW_ID == null) {
			bootoast({
				message: '请选中设备编号',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (startTime == "") {
			bootoast({
				message: '请选中开始时间',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}
		if (endTime == "") {
			bootoast({
				message: '请选中结束时间',
				position: 'top',
				type: 'warning',
				timeout: 1.5,
			});
			return;
		}

		var sensorNames = new Array();
		for (var i = 0; i < SENSOR_ROW_ID.length; i++) {
			sensorNames[i] = 'sensorRowIds=' + SENSOR_ROW_ID[i];
		}
		sensorNames = sensorNames.join('&');
		startTime = 'startTime=' + startTime;
		endTime = 'endTime=' + endTime;
		let companyId = 'companyId=' + label_id

		$.ajax({
			type: 'get',
			url: '/entity_water/selectEntityWaterByCondition?' +
				sensorNames + '&' + startTime + '&' +
				endTime + '&' + companyId,
			success: function (_data) {
				$("#water-chart").empty();
				var renderData = Array();

				$("#water-pie-chart").empty();
                var pieMetaData = Array();
                $("#water-bar-chart").empty();
                var barData = Array();
                var sum = 0;
				for (var i = 0; i < _data.length; i++) {
					renderData[i] = {};
					renderData[i]['CREATED_AT'] = _data[i]['CREATED_AT'];
					renderData[i][_data[i]['NAME']] = _data[i]['VALUE'];

                    var label = _data[i]['NAME'];
                    var flag = 0;
                    for(var j = 0; j < pieMetaData.length; j++){
                        if(pieMetaData[j]['label'] == label){
                            pieMetaData[j]['value']++;
                            barData[j]['value']++;
                            flag = 1;
                            break;
                        }
                    }
                    if(flag == 0){
                        var item = {};
                        item['label'] = label;
                        item['value'] = 1;
                        pieMetaData.push(item);
                        barData.push(item);
                    }

				}




//                console.log(pieMetaData);
//                console.log(barData);

				if (_data.length > 0) {
					$("#hidechartdiv").show();
                    $.ajax({
                        type: 'get',
                        url: '/warning_record/query_names?' +
                            sensorNames + '&' + companyId,
                        success: function (name_data) {
                            Morris.Line({
                                element: 'water-chart',
                                data: renderData,
                                xkey: 'CREATED_AT',
                                ykeys: name_data.names,
                                labels: name_data.names,
                                hideHover: 'auto',
                                resize: true
                            });
                        }
                    });

					Morris.Bar({
                        element: 'water-bar-chart',
                        data: barData,
                        xkey: 'label',
                        ykeys: ["value"],
                        labels: ["新增数量"],
                        barRatio: 0.4,
                        xLabelAngle: 20,
                        hideHover: "auto",
                        barColors: ["#5bc0de"]
                    });


					for(var j = 0; j < pieMetaData.length; j++){
                        sum += pieMetaData[j]['value'];
                    }
                    for(var j = 0; j < pieMetaData.length; j++){
                        var num = pieMetaData[j]['value'];
                        pieMetaData[j]['value'] = ((num/sum)*100).toFixed(2);
                    }
					Morris.Donut({
					    element: 'water-pie-chart',
					    data: pieMetaData,
					    colors: ["#f0ad4e","#3c8dbc", "#f56954", "#00a65a", "#5bc0de", "#D2691E", "#FF7F50"],
                        formatter: function(y) {
                            return y + "%";
                        },
                        hideHover: false,


					});

				} else {
					$("#hidechartdiv").hide();
					bootoast({
						message: '暂无数据',
						position: 'top',
						type: 'warning',
						timeout: 1.5,
					});
					return;
				}

			}
		});
	});